package message;

import lombok.extern.java.Log;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.SQLOutput;

@Log
public class TBorrower implements MessageListener {
    private static String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static String BROKER = ActiveMQConnection.DEFAULT_BROKER_URL;
    private TopicConnection tConnect = null;
    private TopicSession tSession = null;
    private Topic topic = null;

    private double currentRate;

    public TBorrower(String topiccf, String topicName, String rate) {
        try {
            currentRate = Double.parseDouble(rate);

            TopicConnectionFactory tcf = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER);
            tConnect = tcf.createTopicConnection();
            tSession = tConnect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
            topic = tSession.createTopic(topicName);

            // 创建消息监听器 这个是非持久订阅者； 默认情况下，非持久订阅者停下后在启动会丢失发布者之间发布消息
            TopicSubscriber subscriber = tSession.createSubscriber(topic);
            // 创建持久订阅者（受管持久订阅者）
            TopicSubscriber subscriber1 = tSession.createDurableSubscriber(topic,"Borrower1");
            subscriber.setMessageListener(this);// 将自己设置为监听器

            tConnect.start();
            System.out.println("等待 Loan 请求 。。。 ");
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public void onMessage(Message message) {

        // 从消息中获取数据
        try {
            BytesMessage msg = (BytesMessage) message;
            double newRate = msg.readDouble();

            // 如果该比率比当前利率至少低1个百分点，然后在贷款
            if ((currentRate - newRate) >= 1.0) {
                System.out.println("不但款");
            }else {
                System.out.println("单款");
            }

            System.out.println("等待利率更新。。。");

        } catch (JMSException e) {
            log.warning(e + "出错");
        }
    }

    public void exit (){
        try {
            tConnect.close();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        TBorrower tBorrower = new TBorrower("tcf", "TLTopic", "4.5");

        try {
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("TBorrower application started");

            stdin.readLine();

            tBorrower.exit();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
